#include "SetTime.h"

//************************************
// Method:    	tSetTime				对时功能
// Programmer:  lww
// Time:		2018/12/22
// Returns:   	void *
// Parameter: 	void * arg
//************************************
void *tSetTime(void* arg)
{
#define LENGTH	8
#define WRONG_DEAL	{\
	close(sock);\
	RoughDelay_S(10);\
	continue;\
}
	int sock;
	char Recv[8] = { 0 };
	char* Data = Recv;
	int _iLen = 0;
	unsigned int second, millisecond;
	struct timespec sCurTime;

	printf("the Kernel_%s is %d\r\n", "tSetTime_ID", syscall(SYS_gettid));				//< duan20200610

	while (1)
	{
		if (TCP_Client_Init(&sock, 0) == false) { WRONG_DEAL; }
		if (TCP_Client_Connect(&sock, SETTIME_PORT, SETTIME_IP, 5) == false) { WRONG_DEAL; }

		memset(Recv, 0, sizeof(Recv));
		Data = Recv;
		_iLen = 0;
		if (LENGTH != TCP_Recv(&sock, Recv, LENGTH, 10000)) { WRONG_DEAL; }

		MEMREAD(second, Data);
		MEMREAD(millisecond, Data);

		sCurTime.tv_sec = second;
		sCurTime.tv_nsec = millisecond * 1000000;

		RealTime_Set(sCurTime);
		close(sock);
		RoughDelay_S(3600);					//< duan 1204通过线程休眠来实现间断性对时
	}
#undef LENGTH
#undef WRONG_DEAL

//#define LENGTH	8
//	int sock;
//	char Recv[8] = { 0 };
//	char* Data = Recv;
//	int _iLen = 0;
//	unsigned int second, millisecond;
//	struct timespec sCurTime;
//
//	struct timespec ts1 = { 0 };
//	struct timespec ts2 = { 0 };
//	while (1)
//	{ 
//		if (TCP_Client_Init(&sock, 0) == false) { continue; }
//		if (TCP_Client_Connect(&sock, 502, "192.168.0.201", 2) == false) { close(sock);  continue; }
//
//		memset(Recv, 0, sizeof(Recv));
//		_iLen = 0;
//		if (LENGTH != TCP_Recv(&sock, Recv, LENGTH, 500)) { close(sock); continue; }
//		close(sock);
//	}
//#undef LENGTH
}
